/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Marcus Cuda
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using dnAnalytics.Properties;

namespace dnAnalytics.LinearAlgebra.Decomposition
{
    /// <summary>
    /// Class for computing the Singular Value Decomposition of a <see cref="Matrix"/>.
    /// </summary>
    /// <remarks>The actual decomposition is not done until one of the class'
    /// methods is invoked.</remarks>
    public class Svd
    {
        private readonly int mColumns;
        private readonly int mRows;
        private readonly AbstractSvd mSvd;

        /// <summary>
        /// Constructs an Svd object for the given matrix.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="computeVectors">Whether to compute the left and right singular vectors or not.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <b>null</b>.</exception>
        /// <remarks>The actual decomposition is not done until one of the class'
        /// methods is invoked.</remarks>
        public Svd(Matrix matrix, bool computeVectors)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix", Resources.NullParameterException);
            }

            mRows = matrix.Rows;
            mColumns = matrix.Columns;
            if (matrix.GetType() == typeof (DenseMatrix))
            {
                mSvd = new DenseSvd((DenseMatrix)matrix, computeVectors);
            }
            else
            {
                mSvd = new UserSvd(matrix, computeVectors);
            }
        }

        /// <summary>
        /// Returns whether the decomposition converged or not.
        /// </summary>
        /// <returns><b>true</b> if the decomposition converged; <b>false</b> otherwise.</returns>
        public bool Converged()
        {
            return mSvd.Converged();
        }

        ///<summary>Returns the two norm of the <see cref="Matrix"/>.</summary>
        ///<returns>The 2-norm of the <see cref="Matrix"/>.</returns>     
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        public double Norm2()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.Norm2();
        }

        ///<summary>Returns the condition number <b>max(S) / min(S)</b>.</summary>
        ///<returns>The condition number.</returns>
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        public double ConditionNumber()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.ConditionNumber();
        }

        ///<summary>Returns the effective numerical matrix rank.</summary>
        ///<returns>The number of non-negligible singular values.</returns>
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        public int Rank()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.Rank();
        }

        ///<summary>Returns the left singular vectors as a <see cref="Matrix"/>.</summary>
        ///<returns>The left singular vectors. The matrix will be <b>null</b>,
        ///if <b>computeVectors</b> in the constructor is set to false.</returns>
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        public Matrix U()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.U();
        }

        ///<summary>Returns the right singular vectors as a <see cref="Matrix"/>.</summary>
        ///<returns>The right singular vectors. The matrix will be <b>null</b>,
        ///if <b>computeVectors</b> in the constructor is set to false.</returns>
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        ///<remarks>This is the transpose of the V matrix.</remarks>
        public Matrix VT()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.VT();
        }

        ///<summary>Returns the singular values as a diagonal <see cref="Matrix"/>.</summary>
        ///<returns>The singular values as a diagonal <see cref="Matrix"/>.</returns>        
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        public Matrix W()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.W();
        }

        ///<summary>Returns the singular values as a <see cref="Vector"/>.</summary>
        ///<returns>the singular values as a <see cref="Vector"/>.</returns>
        ///<exception cref="ConvergenceFailedException">The decomposition failed to converge to a solution.</exception>
        public Vector S()
        {
            if (!mSvd.Converged())
            {
                throw new ConvergenceFailedException();
            }
            return mSvd.S();
        }

        /// <summary>
        ///  Solves a system of linear equations, <b>AX = B</b>.
        /// </summary>
        /// <param name="input">The right hand side <see cref="Matrix"/>, <b>B</b>.</param>
        /// <returns>The left hand side <see cref="Matrix"/>, <b>X</b>.</returns>
        public Matrix Solve(Matrix input)
        {
            return mSvd.Solve(input);
        }

        /// <summary>
        ///  Solves a system of linear equations, <b>AX = B</b>.
        /// </summary>
        /// <param name="input">The right hand side <see cref="Matrix"/>, <b>B</b>.</param>
        /// <param name="result">The left hand side <see cref="Matrix"/>, <b>X</b>.</param>
        public void Solve(Matrix input, Matrix result)
        {
            mSvd.Solve(input, result);
        }

        /// <summary>
        /// Solves a system of linear equations, <b>Ax = b</b>.
        /// </summary>
        /// <param name="input">The right hand side vector, <b>b</b>.</param>
        /// <returns>The left hand side <see cref="Vector"/>, <b>x</b>.</returns>
        public Vector Solve(Vector input)
        {
            return mSvd.Solve(input);
        }

        /// <summary>
        /// Solves a system of linear equations, <b>Ax = b</b>.
        /// </summary>
        /// <param name="input">The right hand side vector, <b>b</b>.</param>
        /// <param name="result">The left hand side <see cref="Matrix"/>, <b>x</b>.</param>
        public void Solve(Vector input, Vector result)
        {
            mSvd.Solve(input, result);
        }
   }
}